<template>
  <swiper-container ref="mySwiper" class="swiper-container" :space-between="10" :autoplay="false" :slides-per-view="4"
    :grab-cursor="true" :loop="false" :centered-slides="true" :slide-to-clicked-slide="true"
    @swiperslidechange="onSlideChange" :style="{ 'background-image': `url(${activeFilmPoster})` }">
    <swiper-slide class="swiper-slide" v-for="(filmArrangement, index) in filmsArrangement" :key="index"
      @click="onSlideClick(filmArrangement, index)">
      <img :src="filmArrangement.poster" class="swipe-image" :alt="filmArrangement.name" />
    </swiper-slide>
  </swiper-container>

  <van-row justify="center" class="indicator">
    <van-col><van-icon name="arrow-up" /></van-col>
  </van-row>


  <van-row justify="center" class="film-info" :class="{ 'fix-film-info': isFixFilmInfo }" v-if="currentFilm">
    <van-col span="24" class="title">
      <span class="name">{{ currentFilm.name }}</span>
      <span class="grade">{{ currentFilm.grade || 暂无评 }}分</span>
      <van-icon @click="onFilmDetail(currentFilm.filmId)" name="arrow" size="14" color="var(--van-tag-primary-color)"
        style="margin-left: 10px; position: absolute;right:15px;top: 55%;transform: translateY(-50%);height: 20px;" />
    </van-col>
    <van-col span="24" class="info">{{ currentFilm.category }} | {{ currentFilm.runtime }}分钟
      | {{
        currentFilm.director
      }} |{{
        actors
      }}
    </van-col>

  </van-row>


  <van-sticky class="tabs" :offset-top="104">
    <van-tabs v-model:active="activeTab" animated swipeable @click-tab="onClickTab">
      <van-tab v-for="(timestamp, index) in showDate" :key="index" :title="formateDate(timestamp)" class="tab">

        <div v-if="!props.films || props.films.length == 0 || !schedules || schedules.length === 0">
          <div class="no-schedule">
            <van-icon name="video-o" size="150" color="#d2d6dc" />
            <span style="color: #d2d6dc; display: block;"> 暂无场次</span>
          </div>
        </div>
        <div class="tab-content" v-else>
          <!-- 电影排片列表  -->
          <ul class="schedule-list">
            <li class="schedule-item" v-for="schedule in schedules" :key="schedule.scheduleId"
              :class="{ 'disabled': !isSell(schedule.advanceStopMins, schedule.showAt) }">
              <van-row justify="space-between" align="center" :wrap="false">
                <van-col span="6" class="flex">
                  <div class="start-time" :class="{ 'disabled': !isSell(schedule.advanceStopMins, schedule.showAt) }">
                    {{ formattedTimeFromTimestamp(schedule.showAt) }}
                  </div>
                  <div class="end-time" :class="{ 'disabled': !isSell(schedule.advanceStopMins, schedule.showAt) }"> {{
                    formattedTimeFromTimestamp(schedule.endAt) }}散场</div>
                </van-col>
                <van-col span="10" class="flex">
                  <div class="lang" :class="{ 'disabled': !isSell(schedule.advanceStopMins, schedule.showAt) }">{{
                    schedule.filmLanguage }}{{ schedule.imagery }}</div>
                  <div class="hall" :class="{ 'disabled': !isSell(schedule.advanceStopMins, schedule.showAt) }">{{
                    schedule.hallName }}</div>
                </van-col>
                <van-col span="8" class="flex right">
                  <div class="price" :class="{ 'disabled': !isSell(schedule.advanceStopMins, schedule.showAt) }">
                    <i>￥</i>{{ schedule.salePrice / 100 }}<i>起</i>
                  </div>
                  <div class="buy" :class="{ 'disabled': !isSell(schedule.advanceStopMins, schedule.showAt) }">
                    <van-button v-if="isSell(schedule.advanceStopMins, schedule.showAt)" plain hairline type="warning"
                      size="small">购票</van-button>
                    <van-button v-else color="#d2d6dc" hairline plain size="small">停售</van-button>
                  </div>
                </van-col>
              </van-row>
            </li>
          </ul>
        </div>


      </van-tab>
    </van-tabs>
  </van-sticky>
</template>
<script setup>
import { formattedTimeFromTimestamp, isSell } from "@/api/tool.js"
import { format, isToday, isTomorrow, addDays } from 'date-fns'
import { zhCN } from 'date-fns/locale'
import { getCinemaFilmSchedules } from '@/api/index.js'
import { ref, onMounted, useTemplateRef, watch, computed, onUnmounted, nextTick } from 'vue'
import { useRouter } from 'vue-router'
const router = useRouter()
const mySwiper = useTemplateRef('mySwiper')

const props = defineProps({
  films: {
    type: Array,
  },
  cinemaId: {
    type: Number,
  }
})

const filmsArrangement = ref(props.films)

const activeTab = ref(0);

const currentFilm = ref(null) //当前指向电影排片
const currentTimestamp = ref(0) // 当前指向的排片日期时间戳
const schedules = ref([]) // 当前电影排片情况

const activeIndex = ref(0)
const activeFilmPoster = ref('')

const isFixFilmInfo = ref(false)


const actors = computed(() => {
  return currentFilm.value.actors?.map((actor) => actor.name).join(' ')
})

const showDate = computed(() => {
  //console.log('showDate', currentFilm.value.showDate);
  return currentFilm.value.showDate || null
})

// 监听 films 的变化
watch(
  () => props.films,
  (newFilms) => {
    filmsArrangement.value = newFilms
    if (newFilms.length > 0) {
      currentFilm.value = newFilms[0]
      activeFilmPoster.value = newFilms[0].poster
      if (newFilms[0].showDate && newFilms[0].showDate.length > 0) {
        currentTimestamp.value = newFilms[0].showDate[0]
      }
    }
  },
  { immediate: true }, // 立即执行一次
)
// 监听 cinemaId 的变化
watch(
  () => props.cinemaId,
  async (newCinemaId) => {
    if (newCinemaId && currentFilm.value.filmId && currentTimestamp.value) {
      const response = await getCinemaFilmSchedules(newCinemaId, currentFilm.value.filmId, currentTimestamp.value)
      console.log('response', response.data);
    }
  },
)
// 监听 currentFilm  值的变化
watch(
  currentFilm,
  async (newCurrentFilm) => {
    if (newCurrentFilm && newCurrentFilm.filmId && newCurrentFilm.showDate && newCurrentFilm.showDate.length > 0) {
      currentTimestamp.value = newCurrentFilm.showDate[0]
      const response = await getCinemaFilmSchedules(props.cinemaId, newCurrentFilm.filmId, currentTimestamp.value)
      console.log("response:", response.data);
      schedules.value = response.data.schedules
    }
  },
  { immediate: true }, // 立即执行一次
)
// 监听 activeTab  值的变化
watch(
  activeTab,
  async (newActiveTab) => {
    if (showDate.value.length > newActiveTab) {
      currentTimestamp.value = showDate.value[newActiveTab] // 更新当前指向的排片日期时间戳
      const response = await getCinemaFilmSchedules(props.cinemaId, currentFilm.value.filmId, currentTimestamp.value)
      console.log("response:", response.data);
      schedules.value = response.data.schedules
    }
  },
  { immediate: true }, // 立即执行一次
)

onMounted(async () => {
  if (mySwiper.value) {
    // console.log('Swiper initialized:', mySwiper.value.swiper)
  }
  // 添加滚动事件监听
  window.addEventListener('scroll', handleScroll)

  await nextTick()

  if (mySwiper.value) {
    const swiperInstance = mySwiper.value.swiper; // 获取 Swiper 实例
    console.log("Swiper实例化：", swiperInstance);
    // photoIndex.value = parseInt(index);
    swiperInstance.slideTo(0); // 设置当前幻灯片
  }

  // 加载影片排片信息 默认加载第一个影片
  if (currentFilm.value.filmId && currentTimestamp.value) {
    const response = await getCinemaFilmSchedules(props.cinemaId, currentFilm.value.filmId, currentTimestamp.value)
    console.log("response:", response.data);
    schedules.value = response.data.schedules
  }
})

onUnmounted(() => {
  // 移除滚动事件监听
  window.removeEventListener('scroll', handleScroll)
})

const handleScroll = () => {
  if (window.scrollY >= 44) {
    isFixFilmInfo.value = true
  } else {
    isFixFilmInfo.value = false
  }
}

// 点击切换时间戳
const onClickTab = ({ name, title }) => {
  console.log("name:", name);
  console.log("title:", title);
  currentTimestamp.value = showDate.value[parseInt(name)] // 更新当前指向的排片日期时间戳
  console.log("currentTimestamp:", currentTimestamp.value);
  console.log("当前点击索引：", activeTab.value);

}

// 点击电影详情
const onFilmDetail = (filmId) => {
  console.log("filmId:", filmId);

  router.push({ name: 'filmDetail', params: { id: filmId } })
}



const onSlideClick = async (filmArrangement, index) => {
  // console.log('电影名称：', filmArrangement.name)
  // activeFilmPoster.value = props.films[index].poster
  // currentFilm.value = filmArrangement // 当前电影

  // await nextTick()

  // if (mySwiper.value) {
  //   const swiperInstance = mySwiper.value.swiper; // 获取 Swiper 实例
  //   console.log("Swiper实例化：", swiperInstance);
  //   // photoIndex.value = parseInt(index);
  //   swiperInstance.slideTo(index); // 设置当前幻灯片
  // }
  // 查找对应电影排片情况
}


const onSlideChange = (event) => {
  console.log('Slide changed to:', event.detail[0].activeIndex)
  // activeIndex.value = swiper.activeIndex
  activeFilmPoster.value = props.films[event.detail[0].activeIndex].poster
  //请求对应的电影排片数据
  currentFilm.value = filmsArrangement.value[event.detail[0].activeIndex]

}

// 格式化日期的方法
const formateDate = (timestamp) => {
  const date = new Date(timestamp * 1000); // 将时间戳转换为 Date 对象

  if (isToday(date)) {
    return `今天${format(date, 'M月d日', { locale: zhCN })}`;
  } else if (isTomorrow(date)) {
    return `明天${format(date, 'M月d日', { locale: zhCN })}`;
  } else if (format(date, 'yyyy-MM-dd') === format(addDays(new Date(), 2), 'yyyy-MM-dd')) {
    return `后天${format(date, 'M月d日', { locale: zhCN })}`;
  } else {
    const weekday = format(date, 'EEEE', { locale: zhCN });
    return `${weekday}${format(date, 'M月d日', { locale: zhCN })}`;
  }
};

</script>

<style scoped>
.swiper-container {
  position: relative;
  width: 100%;
  height: 100%;
  padding: 10px 0;
}

/* 这段样式代码用于创建一个具有模糊效果和动态变化的背景层，增强了视觉效果同时不影响主要内容的展示 */
.swiper-container::before {
  width: 100%;
  height: 100%;
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-size: cover;
  background-position: center;
  backdrop-filter: blur(15px);
  -webkit-filter: blur(15px);
  filter: blur(15px);
  z-index: -1;
  animation: moveBackground 10s linear infinite;
  /* 确保伪元素在内容后面 */
}

@keyframes moveBackground {
  0% {
    background-position: 0% 50%;
  }

  50% {
    background-position: 100% 50%;
  }

  100% {
    background-position: 0% 50%;
  }
}

.swiper-slide {
  font-size: 18px;
  background: #fff;
  display: flex;
  justify-content: center;
  align-items: center;
  transition: 300ms;
  transform: scale(0.8);
}

.swiper-slide-active,
.swiper-slide-duplicate-active {
  transform: scale(1);
}

.swiper-slide-active img,
.swiper-slide-duplicate-active img {
  display: block;
  transform: scale(1);
}

.swiper-slide img {
  display: block;
  min-width: 90px;
  min-height: 130px;
}

.film-info {
  text-align: center;
  background-color: #fff;
  border-bottom: 1px solid #f4f4f4;
  height: 60px;
  width: 100%;
}

.film-info.fix-film-info {
  position: fixed;
  top: 44px;
  z-index: 300;
}



.film-info .title {
  font-size: 15px;
  color: #191a1b;
}

.film-info .info {
  text-align: center;
  height: 18px;
  color: #797d82;
  font-size: 13px;
  padding: 0 12%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.name {
  font-size: 15px;
  color: #191a1b;
  padding-right: 5px;
}

.grade {
  font-size: 16px;
  font-style: italic;
  color: #ffb232;
}

.tabs {
  position: sticky;
  top: 104px;
  z-index: 299;
  height: auto;

  /* 确保高度自适应 */
}

.van-tabs {
  height: auto;
  /* 确保高度自适应 */
}

.tab-content {
  /* 设置一个最小高度 */
  /* min-height: calc(100vh - 104px); */
  min-height: calc(100vh - 450px);
  /* 调整高度以适应屏幕 */
  overflow-y: auto;
  z-index: 301;
  scrollbar-width: none;
  text-align: center;
  /* padding-bottom: 70px; */
  /* 添加底部填充 */
}

.tab-content::-webkit-scrollbar {
  display: none;
}


.tab-content .schedule-list {
  list-style-type: none;

  margin: 0;
  height: auto;
  overflow-y: auto;
  z-index: 297;
  padding-bottom: 44px;
  /*  修复列表底部 被隐藏的bug */

}

.tab-content .schedule-item {
  position: relative;
  background: #fff;
  box-sizing: border-box;
  padding: 15px;
  width: 100%;
  border-top: 1px solid #f4f4f4;
}

/* li.schedule-item.disabled {
  color: #d2d6dc !important;
} */

.start-time.disabled,
.end-time.disabled,
.lang.disabled,
.hall.disabled,
.price.disabled {
  color: #d2d6dc
}


.flex {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  justify-content: space-between;
  flex-wrap: nowrap;
  padding-left: 14px;
}

.start-time {
  font-size: 15px;
  color: #191a1b;
}

.end-time {
  font-size: 13px;
  color: #797d82;
}

.lang {
  font-size: 15px;
  color: #191a1b;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap
}

.hall {
  font-size: 13px;
  color: #797d82;
  margin-top: 2px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.right {
  flex-direction: row;
  align-items: center;
}

.price {
  font-size: 15px;
  line-height: 25px;
  color: #ff5f16
}


.price i {
  font-size: 10px;
}


.no-schedule {
  text-align: center;
}
</style>
